
import { defineStore } from 'pinia'
import { verityService, sm2Encrypt } from "@/services/auth/verity";
import { Message } from '@arco-design/web-vue';
import router from '@/router';
export const useUserStore = defineStore('user', () => {
    const token = ref<string>('');
    const user = ref<any>(null);
    const isLogin = computed(() => token.value !== '');
    const login = async (loginForm: any, redirect: string = '/') => {
        try {
            // 获取公钥
            const { data } = await verityService.publicKey("login") as any;
            const { publicId, publicKey } = data;
            // 加密登录信息
            const loginParams = {
                publicId,
                account: sm2Encrypt(loginForm.account, publicKey),
                password: sm2Encrypt(loginForm.password, publicKey),
            };
            // 执行登录
            const res = await loginService.login(loginParams) as any;
            if (!res.ok) {
                Message.error(res.message);
                return false;
            }
            // 更新 store 状态（插件会自动持久化）
            token.value = res.data.token;
            user.value = res.data;

            Message.success("登录成功");
            if (redirect) {
                router.push(redirect);
            }
            return true;
        }
        catch (error) {
            Message.error("登录失败，请重试");
            console.error(error);
            return false;
        }
    }
    const logout = async () => {
        try {
            // 调用后端登出接口（如果需要）
            await loginService.logout();
        } catch (error) {
            console.error("登出接口调用失败:", error);
            // 即使后端失败，也继续清除本地状态
        } finally {
            // 重置 store 状态（插件会自动清除持久化数据）
            token.value = '';
            user.value = null;
            // 跳转到登录页
            router.push('/console/login');
        }
    }
    const hasPermission = (permission: string) => {
        return user.value?.permissions?.includes(permission) || false;
    }
    return {
        token,
        user,
        isLogin,
        login,
        logout,
        hasPermission,
    }
}, {
    persist: {
        key: 'user-store', // 指定唯一键名
        storage: localStorage, // 或 sessionStorage
        pick: ['token', 'user'], // 明确指定要持久化的字段
    },
})
